import {
  GraphQLObjectType,
  GraphQLList,
  GraphQLString,
  GraphQLID,
  GraphQLNonNull,
  GraphQLBoolean,
} from 'graphql';

import relayNode from '../relay';

import { attributeFields, resolver } from 'graphql-sequelize';
import CompanyType from './CompanyType';

import {
  fromGlobalId,
  globalIdField,
  connectionArgs,
  connectionFromArray,
} from 'graphql-relay';

import { User, Company, Wtp, Profile } from '../models';
import { connectionFromType, connectionFromModel } from '../connection';
import WtpType from "./WtpType";
import ProfileType from "./ProfileType";

const UserType = new GraphQLObjectType({
  name: "User",
  fields: () => Object.assign(
    {},
    attributeFields(User, {
      exclude: ['password'],
    }),
    {
      id: globalIdField(User.id),
      company: {
        type: CompanyType,
        args: {
          id: {
            type: GraphQLID,
          },
        },
        resolve: async (user, { id }) => {
          if (id) {
            return await Company.findById(parseInt(fromGlobalId(id).id, 10))
          } else {
            return await Company.findById(user.company_id)
          }
        }
      },
      companies: {
        type: connectionFromType('companies', CompanyType).connection,
        args: {
          ...connectionArgs,
        },
        resolve: async (user, { ...args }) => {
          return connectionFromModel(Company, {}, args);
        }
      },
      wtps: {
        type: connectionFromType('wtps', WtpType).connection,
        args: {
          ...connectionArgs,
        },
        resolve: async (user, { ...args }) => {
          return connectionFromModel(Wtp, {}, args);
        },
      },
      wtp: {
        type: WtpType,
        args: {
          id: {
            type: GraphQLID,
          },
        },
        resolve: async (user, { id }) => await Wtp.findById(parseInt(fromGlobalId(id).id, 10))
      },
      profile: {
        type: ProfileType,
        args: {
          id: {
            type: GraphQLID,
          },
        },
        resolve: async (user, {id}) => await Profile.findById(parseInt(fromGlobalId(id).id, 10))
      },
      profiles: {
        type: connectionFromType('profiles', ProfileType).connection,
        args: {
          ...connectionArgs,
        },
        resolve: async (user, { ...args }) => {
          return connectionFromModel(Profile, {}, args);
        }
      }
    },
  ),
  interfaces: [relayNode.nodeInterface],
});

export default UserType;
